package com.qf.mrboot1.service.impl;

import com.qf.mrboot1.entity.Order;
import com.qf.mrboot1.dao.OrderDao;
import com.qf.mrboot1.result.ResponseData;
import com.qf.mrboot1.result.ResultCode;
import com.qf.mrboot1.service.OrderService;
import com.qf.mrboot1.util.SmsUtil;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

/**
 * (Order)表服务实现类
 *
 * @author makejava
 * @since 2021-06-02 09:47:41
 */
@Service("orderService")
public class OrderServiceImpl implements OrderService {
    @Resource
    private OrderDao orderDao;

    /**
     * 通过ID查询单条数据
     *
     * @param oId 主键
     * @return 实例对象
     */
    @Override
    public Order queryById(Integer oId) {
        return this.orderDao.queryById(oId);
    }

    /**
     * 查询多条数据
     *
     * @param offset 查询起始位置
     * @param limit  查询条数
     * @return 对象列表
     */
    @Override
    public List<Order> queryAllByLimit(int offset, int limit) {
        return this.orderDao.queryAllByLimit(offset, limit);
    }

    /**
     * 新增数据
     *
     * @param order 实例对象
     * @return 实例对象
     */

    @Transactional
    @Override
    public ResponseData insert(Order order) {
        try {
            String code = SmsUtil.SendMs(order.getTel());
            if (code == null) {
                return new ResponseData("000201", "短信发送失败", null);
            }
            order.setCode(code);
            order.setSubtime(new Date());
            order.setStatus(0);
            int insert = orderDao.insert(order);
            if (insert > 0) {
                return new ResponseData(ResultCode.SUCCESS, null);
            } else {
                return new ResponseData(ResultCode.FAILED, null);
            }
        }catch (Exception e){
            e.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return null;
        }

    }


    /**
     * 修改数据
     *
     * @param order 实例对象
     * @return 实例对象
     */
    @Override
    public Order update(Order order) {
        this.orderDao.update(order);
        return this.queryById(order.getOId());
    }

    /**
     * 通过主键删除数据
     *
     * @param oId 主键
     * @return 是否成功
     */
    @Override
    public boolean deleteById(Integer oId) {
        return this.orderDao.deleteById(oId) > 0;
    }
}
